import serial
import time
import scipy.signal as sig
import numpy as np
import matplotlib.pyplot as plt
from util.data_deal import get_feature


# try:
# 打开串口，并得到串口对象
fs = 1000
my_serial = serial.Serial()
my_serial.port = 'COM3'
my_serial.baudrate = 115200
my_serial.stopbits = 1
my_serial.timeout = 5
my_serial.open()
if my_serial.is_open:
    print('串口已经打开')

time.sleep(1)

start = [0x55, 0xbb, 0x04]
start_hex = bytearray(start)
print(start_hex)
my_serial.write(start_hex)

count = 0
inner_count = 0
temp_buffer = []
ch1_data = []
ch2_data = []
ch3_data = []
ch4_data = []
all_date = []
while True:
    if inner_count == 10000:
        print(ch1_data)
        print(ch2_data)
        print(ch3_data)
        print(ch4_data)
        ch1_feature = get_feature(np.array(ch1_data), fs)
        ch2_feature = get_feature(np.array(ch2_data), fs)
        ch3_feature = get_feature(np.array(ch3_data), fs)
        ch4_feature = get_feature(np.array(ch4_data), fs)
        if ch1_feature is not None:
            print('通道1检测到' + str(len(ch1_feature)) + '个活动：')
            print(ch1_feature)
        if ch2_feature is not None:
            print('通道2检测到' + str(len(ch2_feature)) + '个活动：')
            print(ch2_feature)
        if ch3_feature is not None:
            print('通道3检测到' + str(len(ch3_feature)) + '个活动：')
            print(ch3_feature)
        if ch4_feature is not None:
            print('通道4检测到' + str(len(ch4_feature)) + '个活动：')
            print(ch4_feature)
        ch1_data = []
        ch2_data = []
        ch3_data = []
        ch4_data = []
        all_date = []
        inner_count = 0
        # break
    if my_serial.in_waiting:
        read_buf = my_serial.read()
        count += 1
        temp_buffer.append(read_buf)
        if count == 10:
            # print(temp_buffer)
            if temp_buffer[0].hex() == '55' and temp_buffer[1].hex() == 'aa':
                ch1_temp_data = '0x' + temp_buffer[2].hex() + temp_buffer[3].hex()
                ch2_temp_data = '0x' + temp_buffer[4].hex() + temp_buffer[5].hex()
                ch3_temp_data = '0x' + temp_buffer[6].hex() + temp_buffer[7].hex()
                ch4_temp_data = '0x' + temp_buffer[8].hex() + temp_buffer[9].hex()
                ch1_data.append(int(ch1_temp_data, 16))
                ch2_data.append(int(ch2_temp_data, 16))
                ch3_data.append(int(ch3_temp_data, 16))
                ch4_data.append(int(ch4_temp_data, 16))
                inner_count += 1
            temp_buffer = []
            count = 0
# print('ch1', ch1_data)
# print('ch2', ch2_data)
# print('ch3', ch3_data)
# print('ch4', ch4_data)
end = [0x55, 0xbb, 0x00]
end_hex = bytearray(end)
print(my_serial.write(end_hex))
print(end_hex)
my_serial.close()

# except Exception as e:
#     print('----发生异常----', e)

